package com.weixin.servlet.backstage;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.weixin.service.IBackstageService;
import com.weixin.service.impl.BackstageServiceImpl;
import com.weixin.vo.Bank;
import com.weixin.vo.MemberEdit;
import com.weixin.vo.MemberList;
import com.weixin.vo.MemberType;

/**
 * 后台管理的servlet，处理用户管理页面
 * @author 唐鑫明
 *
 */
@WebServlet("/BackstageServlet/*")
public class BackstageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	IBackstageService backstageService =  new BackstageServiceImpl();

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String pathInfo = request.getPathInfo().substring(1);
		if("listMemberInfo".equals(pathInfo)) {
			listMemberInfo(request,response);
		}else if("editMemberState".equals(pathInfo)) {
			editMemberState(request,response);
		}else if("preAddMember".equals(pathInfo)) {
			preAddMember(request,response);
		}else if("addMember".equals(pathInfo)) {
			addMember(request,response);
		}else if("preEditMember".equals(pathInfo)) {
			preEditMember(request,response);
		}else if("editMember".equals(pathInfo)) {
			editMember(request,response);
		}else if("deleteMember".equals(pathInfo)) {
			deleteMember(request,response);
		}else if("deleteSelectMember".equals(pathInfo)) {
			deleteSelectMember(request,response);
		}else if("resetMemberPass".equals(pathInfo)) {
			resetMemberPass(request,response);
		}else if("resetSelectMemberPass".equals(pathInfo)) {
			resetSelectMemberPass(request,response);
		}
	}
	/**
	 * 初始化选中会员的密码
	 * @param request
	 * @param response
	 */
	private void resetSelectMemberPass(HttpServletRequest request, HttpServletResponse response) {
		String[] user_ids = request.getParameterValues("user_id");
		try {
			//调用业务层的方法根据会员ID初始化会员的密码
			boolean b = backstageService.resetSelectMemberPass(user_ids);
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 初始化单个会员密码
	 * @param request
	 * @param response
	 */
	private void resetMemberPass(HttpServletRequest request, HttpServletResponse response) {
		int user_id = 0;
		if(request.getParameter("user_id")!=null&&!(request.getParameter("user_id").equals("")) ) {
			user_id = Integer.valueOf(request.getParameter("user_id"));
		}
		try {
			//调用业务层的方法根据会员ID初始化该会员的密码
			boolean b = backstageService.resetMemberPass(user_id);
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 删除选中会员信息
	 * @param request
	 * @param response
	 */
	private void deleteSelectMember(HttpServletRequest request, HttpServletResponse response) {
		String[] user_ids = request.getParameterValues("user_id");
		try {
			//调用业务层的方法删除选中的会员
			boolean b = backstageService.deleteSelectMember(user_ids);
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 删除单个会员
	 * @param request
	 * @param response
	 */
	private void deleteMember(HttpServletRequest request, HttpServletResponse response) {
		int user_id = 0;
		if(request.getParameter("user_id")!=null||!(request.getParameter("user_id").equals(""))) {
			user_id = Integer.valueOf(request.getParameter("user_id"));
		}
		try {
			//调用业务层的方法根据会员ID删除会员
			boolean b = backstageService.deleteMember(user_id);
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修改会员信息
	 * @param request
	 * @param response
	 */
	private void editMember(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		//创建会员对象，存放新会员的信息
		MemberEdit memberEdit = new MemberEdit();
		//获取新会员的信息
		int user_id=0;
		if(request.getParameter("user_account")!=null&&!("".equals(request.getParameter("user_account")))) {
			user_id = Integer.valueOf(request.getParameter("user_account"));
		}
		String user_name = null;
		if(request.getParameter("user_name")!=null&&!("".equals(request.getParameter("user_name")))) {
			user_name = request.getParameter("user_name");
		}
		String user_gender = "男";
		if(request.getParameter("gender")!=null&&!("".equals(request.getParameter("gender")))) {
			user_gender = request.getParameter("gender");
		}
		String user_tel = null;
		if(request.getParameter("user_tel")!=null&&!("".equals(request.getParameter("user_tel")))) {
			user_tel = request.getParameter("user_tel");
		}
		String user_idcard = null;
		if(request.getParameter("user_idcard")!=null&&!("".equals(request.getParameter("user_idcard")))) {
			user_idcard = request.getParameter("user_idcard");
		}
		String user_email = null;
		if(request.getParameter("user_email")!=null&&!("".equals(request.getParameter("user_email")))) {
			user_email = request.getParameter("user_email");
		}
		int user_ems = 0;
		if(request.getParameter("user_ems")!=null&&!("".equals(request.getParameter("user_ems")))) {
			user_ems = Integer.valueOf(request.getParameter("user_ems"));
		}
		String user_tuijian = null;
		if(request.getParameter("user_tuijian")!=null&&!("".equals(request.getParameter("user_tuijian")))) {
			user_tuijian = request.getParameter("user_tuijian");
		}
		int bank_id = 0;
		if(request.getParameter("bank_id")!=null&&!("".equals(request.getParameter("bank_id")))) {
			bank_id = Integer.valueOf(request.getParameter("bank_id"));
		}
		String user_cardNo = null;
		if(request.getParameter("user_cardNo")!=null&&!("".equals(request.getParameter("user_cardNo")))) {
			user_cardNo = request.getParameter("user_cardNo");
		}
		String user_pwd = "123456";
		if(request.getParameter("user_pwd")!=null&&!("".equals(request.getParameter("user_pwd")))) {
			user_pwd = request.getParameter("user_pwd");
		}
		int user_tpwd = 0;
		if(request.getParameter("user_tpwd")!=null&&!("".equals(request.getParameter("user_tpwd")))) {
			user_tpwd = Integer.valueOf(request.getParameter("user_tpwd"));
		}
		int state_id = 1;
		if(request.getParameter("state")!=null&&!("".equals(request.getParameter("state")))) {
			state_id = Integer.valueOf(request.getParameter("state"));
		}
		Date user_time = null;
		if(request.getParameter("user_time")!=null&&!("".equals(request.getParameter("user_time")))) {
			try {
				user_time = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss").parse(request.getParameter("user_time"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		int type_id = 0;
		if(request.getParameter("type_id")!=null&&!("".equals(request.getParameter("type_id")))) {
			type_id = Integer.valueOf(request.getParameter("type_id"));
		}
		String user_address = null;
		if(request.getParameter("user_address")!=null&&!("".equals(request.getParameter("user_address")))) {
			user_address = request.getParameter("user_address");
		}
		
		memberEdit.setUser_id(user_id);
		memberEdit.setUser_name(user_name);
		memberEdit.setUser_gender(user_gender);
		memberEdit.setUser_idcard(user_idcard);
		memberEdit.setUser_tel(user_tel);
		memberEdit.setUser_email(user_email);
		memberEdit.setUser_ems(user_ems);
		memberEdit.setUser_tuijian(user_tuijian);
		memberEdit.setBank_id(bank_id);
		memberEdit.setUser_cardNo(user_cardNo);
		memberEdit.setUser_pwd(user_pwd);
		memberEdit.setUser_tpwd(user_tpwd);
		memberEdit.setState_id(state_id);
		memberEdit.setRole_id(1112+"");
		memberEdit.setUser_address(user_address);
		memberEdit.setActi_id(0);
		memberEdit.setUser_money(0.0);
		memberEdit.setIntegral(0);
		memberEdit.setType_id(type_id);
		
		try {
			boolean b = false;
			//调用业务层的方法根据ID查找对应的会员信息
			MemberList member = backstageService.selectMemberById(user_id);
			//调用业务层的方法修改会员信息
			if(!member.getUser_time().equals(user_time)) {
				memberEdit.setUser_time(new Date());
			    b = backstageService.editMember(memberEdit, user_id);
			}else {
				memberEdit.setUser_time(user_time);
			    b = backstageService.editMember(memberEdit, user_id);
			}
			String result="修改失败";
			if(b) {
				result="修改成功";
				request.setAttribute("result", result);
				request.getRequestDispatcher("/BackstageServlet/listMemberInfo").forward(request, response);
			}else {
				request.setAttribute("result", result);
				request.getRequestDispatcher("/BackstageServlet/listMemberInfo").forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 预修改会员信息
	 * @param request
	 * @param response
	 */
	private void preEditMember(HttpServletRequest request, HttpServletResponse response) {
		//设置编码
		try {
			request.setCharacterEncoding("utf-8");
			response.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		int user_id = 0;
		if( request.getParameter("user_id")!=null&&!(request.getParameter("user_id").equals("")) ) {
			user_id = Integer.valueOf(request.getParameter("user_id"));
		}
		try {
			//调用业务层的方法获取银行信息
			List<Bank> bankInfoList = backstageService.selectBankInfo();
			//调用业务层的方法获取会员类型信息
			List<MemberType> memberTypeList = backstageService.selectTypeInfo();
			//调用业务层的方法根据ID查找对应的会员信息
			MemberList member = backstageService.selectMemberById(user_id);
			Date date = member.getUser_time();
			String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
			//将信息通过json格式的字符串传递到前端页面展示
			response.getWriter().println("["+new Gson().toJson(member)+","+new Gson().toJson(bankInfoList)+","+new Gson().toJson(memberTypeList)+","+new Gson().toJson(time)+"]");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 添加会员
	 * @param request
	 * @param response
	 */
	private void addMember(HttpServletRequest request, HttpServletResponse response) {
		try {
			request.setCharacterEncoding("utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		}
		//创建会员对象，存放新会员的信息
		MemberEdit memberEdit = new MemberEdit();
		//获取新会员的信息
		int user_id=0;
		if(request.getParameter("user_account")!=null&&!("".equals(request.getParameter("user_account")))) {
			user_id = Integer.valueOf(request.getParameter("user_account"));
		}
		String user_name = null;
		if(request.getParameter("user_name")!=null&&!("".equals(request.getParameter("user_name")))) {
			user_name = request.getParameter("user_name");
		}
		String user_gender = "男";
		if(request.getParameter("gender")!=null&&!("".equals(request.getParameter("gender")))) {
			user_gender = request.getParameter("gender");
		}
		String user_tel = null;
		if(request.getParameter("user_tel")!=null&&!("".equals(request.getParameter("user_tel")))) {
			user_tel = request.getParameter("user_tel");
		}
		String user_idcard = null;
		if(request.getParameter("user_idcard")!=null&&!("".equals(request.getParameter("user_idcard")))) {
			user_idcard = request.getParameter("user_idcard");
		}
		String user_email = null;
		if(request.getParameter("user_email")!=null&&!("".equals(request.getParameter("user_email")))) {
			user_email = request.getParameter("user_email");
		}
		int user_ems = 0;
		if(request.getParameter("user_ems")!=null&&!("".equals(request.getParameter("user_ems")))) {
			user_ems = Integer.valueOf(request.getParameter("user_ems"));
		}
		String user_tuijian = null;
		if(request.getParameter("user_tuijian")!=null&&!("".equals(request.getParameter("user_tuijian")))) {
			user_tuijian = request.getParameter("user_tuijian");
		}
		int bank_id = 0;
		if(request.getParameter("bank_id")!=null&&!("".equals(request.getParameter("bank_id")))) {
			bank_id = Integer.valueOf(request.getParameter("bank_id"));
		}
		String user_cardNo = null;
		if(request.getParameter("user_cardNo")!=null&&!("".equals(request.getParameter("user_cardNo")))) {
			user_cardNo = request.getParameter("user_cardNo");
		}
		String user_pwd = "123456";
		if(request.getParameter("user_pwd")!=null&&!("".equals(request.getParameter("user_pwd")))) {
			user_pwd = request.getParameter("user_pwd");
		}
		int user_tpwd = 0;
		if(request.getParameter("user_tpwd")!=null&&!("".equals(request.getParameter("user_tpwd")))) {
			user_tpwd = Integer.valueOf(request.getParameter("user_tpwd"));
		}
		int state_id = 1;
		if(request.getParameter("state")!=null&&!("".equals(request.getParameter("state")))) {
			state_id = Integer.valueOf(request.getParameter("state"));
		}
		Date user_time = null;
		if(request.getParameter("user_time")!=null&&!("".equals(request.getParameter("user_time")))) {
			try {
				user_time = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss").parse(request.getParameter("user_time"));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		int type_id = 0;
		if(request.getParameter("type_id")!=null&&!("".equals(request.getParameter("type_id")))) {
			type_id = Integer.valueOf(request.getParameter("type_id"));
		}
		String user_address = null;
		if(request.getParameter("user_address")!=null&&!("".equals(request.getParameter("user_address")))) {
			user_address = request.getParameter("user_address");
		}
		
		memberEdit.setUser_id(user_id);
		memberEdit.setUser_name(user_name);
		memberEdit.setUser_gender(user_gender);
		memberEdit.setUser_idcard(user_idcard);
		memberEdit.setUser_tel(user_tel);
		memberEdit.setUser_email(user_email);
		memberEdit.setUser_ems(user_ems);
		memberEdit.setUser_tuijian(user_tuijian);
		memberEdit.setBank_id(bank_id);
		memberEdit.setUser_cardNo(user_cardNo);
		memberEdit.setUser_pwd(user_pwd);
		memberEdit.setUser_tpwd(user_tpwd);
		memberEdit.setState_id(state_id);
		memberEdit.setUser_time(user_time);
		memberEdit.setRole_id(1112+"");
		memberEdit.setUser_address(user_address);
		memberEdit.setActi_id(0);
		memberEdit.setUser_money(0.0);
		memberEdit.setIntegral(0);
		memberEdit.setType_id(type_id);
		
		try {
			//调用业务层 的方法查询在数据库中是否存在该会员信息
			MemberList memberById = backstageService.selectMemberById(user_id);
			if(memberById!=null) {
				request.getRequestDispatcher("/BackstageServlet/listMemberInfo?result=该用户已存在").forward(request, response);
			}else {
				//调用业务层的方法添加新会员信息
				boolean b = backstageService.addMember(memberEdit);
				if(b) {
					request.getRequestDispatcher("/BackstageServlet/listMemberInfo?resule=新增成功").forward(request, response);
				}else {
					request.getRequestDispatcher("/BackstageServlet/listMemberInfo?result=新增失败").forward(request, response);
				}
			}
			
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}

	/**
	 * 预添加会员
	 * @param request
	 * @param response
	 */
	private void preAddMember(HttpServletRequest request, HttpServletResponse response) {
		//设置编码
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		try {
			//调用业务层的方法获取银行信息
			List<Bank> bankInfoList = backstageService.selectBankInfo();
			//调用业务层的方法获取会员类型信息
			List<MemberType> memberTypeList = backstageService.selectTypeInfo();
			//将信息通过json格式的字符串传递到前端页面展示
			response.getWriter().println("["+new Gson().toJson(bankInfoList)+","+new Gson().toJson(memberTypeList)+"]");
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 修改会员状态(启用/禁止)
	 * @param request
	 * @param response
	 */
	private void editMemberState(HttpServletRequest request, HttpServletResponse response) {
		int user_id = 0 ;
		if(request.getParameter("user_id")!=null) {
			user_id = Integer.valueOf(request.getParameter("user_id"));
		}
		String state_name = null;
		if(request.getParameter("state_name")!=null) {
			state_name = request.getParameter("state_name");
		}
		int state_id = 0;
		try {
			//调用业务层的方法根据状态ID获取状态名
			if(state_name.equals("启用")) {
				state_id = backstageService.selectStateIdByName("禁用");
			}else if(state_name.equals("禁用")) {
				state_id = backstageService.selectStateIdByName("启用");
			}
			
			//调用业务层的方法根据会员ID修改会员状态(启用/禁止)
			boolean b = backstageService.editMemberState(user_id, state_id);
			if(b) {
				response.getWriter().println(1);
			}else {
				response.getWriter().println(0);
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * 显示会员信息
	 * @param request
	 * @param response
	 */
	private void listMemberInfo(HttpServletRequest request, HttpServletResponse response) {
		//获取会员姓名
		String user_name = request.getParameter("user_name");
		//设置默认显示第一页
		int pageNum = 1;
		if(request.getParameter("pageNum")!=null) {
			pageNum = Integer.valueOf(request.getParameter("pageNum"));
		}
		//设置每页大小
		int pageSize = 6;
		try {
			//调用业务层的方法获取会员信息
			List<MemberList> memberInfoList = backstageService.selectMemberInfo(user_name,pageNum,pageSize);
			//调用业务层的方法获取一共有多少个会员
			long count = backstageService.selectMemberCount(user_name);
			//计算一共有几页
			int pageCount = (int)Math.ceil(count*1.0/pageSize);
			//request绑定属性
			request.setAttribute("memberInfoList", memberInfoList);
			//绑定user_name进行表单回填
			request.setAttribute("user_name", user_name);
			request.setAttribute("pageNum",pageNum);
			request.setAttribute("pageCount",pageCount);
			//跳转到member_list.jsp页面处理数据
			request.getRequestDispatcher("/pages/houtai/member/member_list.jsp").forward(request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

}
